package com.example.pt.controller;

import com.example.pt.entity.UserTransferStats;
import com.example.pt.service.UserTransferStatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/tracker")
@CrossOrigin(origins = "*")
public class TrackerStatsController {
    
    private static final Logger logger = LoggerFactory.getLogger(TrackerStatsController.class);
    
    @Autowired
    private UserTransferStatsService userTransferStatsService;
    
    /**
     * 接收并处理来自Chihaya的用户上传下载统计信息
     * 
     * @param stats 统计信息
     * @return 处理结果
     */
    @PostMapping("/stats")
    public ResponseEntity<Map<String, Object>> updateStats(@RequestBody UserTransferStats stats) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            logger.info("收到上传下载统计：用户ID={}, 种子Hash={}, 上传量={}, 下载量={}",
                    stats.getUserId(), stats.getInfoHash(), stats.getUploaded(), stats.getDownloaded());
            
            boolean result = userTransferStatsService.updateUserTransferStats(stats);
            
            response.put("success", result);
            if (result) {
                response.put("message", "统计信息更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("message", "统计信息更新失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            logger.error("处理上传下载统计异常", e);
            response.put("success", false);
            response.put("message", "处理异常：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 